#include "GameScene.h"
#include "GameGlobal.h"
#include "GameDefine.h"
#include "InlineFunc.h"
#include "RoomScene.h"
#include "LoginScene.h"
#include "CocosHelper.h"
#include "SimpleAudioEngine.h"
#include "StringTable.h"
using namespace cocos2d;
using namespace CocosDenshion;

anFight CGameScene::s_initData;

void CGameScene::SetInitPactet(const anFight &p)
{
    memcpy(&s_initData, &p, sizeof(GameInitPacket));
}

bool CGameScene::init()
{
    if(!CCLayer::init())
    {
        return false;
    }
    
    return true;
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::onEnter()
{
    CCLayer::onEnter();
    
    srand((unsigned int)time(NULL));
	this->setIsTouchEnabled(true);

	m_pCurScene = CSceneManager::CreateScene(1);
	addChild(m_pCurScene);
	m_pCurScene->initScene();
	m_pLayUI = CCLayer::node();
	addChild(m_pLayUI, 100);

    InitData();
    InitUI();
    InitPlayers();
    
	m_pCurScene->ScaleMainWithCenter(m_pArcherLocal->GetPos(), 1.0f, 1.0f);
    schedule(schedule_selector(CGameScene::OnUpdate));

	SimpleAudioEngine::sharedEngine()->playBackgroundMusic("Music/background.mp3", true);
}

void CGameScene::onExit()
{
	SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
	CCLayer::onExit();
}
//------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::keyboardWillShow(cocos2d::CCIMEKeyboardNotificationInfo& info)
{
	// 响应了两遍。。

	float AdjustVertY = CCRect::CCRectGetMaxY(info.end) - CCRect::CCRectGetMinY(GetRect(m_pTFRoomSend));

	if(m_lastAdjustVertY > 0)
	{
		return;
	}
	CCArray * children = getChildren();
	CCPoint pos;

	pos = m_pTFRoomSend->getPosition();
	pos.y += AdjustVertY;
	m_pTFRoomSend->setPosition(pos);


	pos = m_pBtnSend->getPosition();
	pos.y += AdjustVertY;
	m_pBtnSend->setPosition(pos);


	m_lastAdjustVertY = AdjustVertY;

}

//------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::keyboardWillHide(cocos2d::CCIMEKeyboardNotificationInfo& info)
{

	m_lastAdjustVertY = m_lastAdjustVertY;
	CCArray * children = getChildren();

	
	CCPoint pos;

		pos = m_pTFRoomSend->getPosition();
		pos.y -= m_lastAdjustVertY;
		m_pTFRoomSend->setPosition(pos);

		pos = m_pBtnSend->getPosition();
		pos.y -= m_lastAdjustVertY;
		m_pBtnSend->setPosition(pos);


	m_lastAdjustVertY = 0;
}
//-------------------------------------------------------------------------------------------------------------/
void CGameScene::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	// 1判定是否正在飞行
	// 2判定是否点中任务
	// 3其他


	if(CCRect::CCRectContainsPoint(GetRect(m_pTFRoomSend), m_pLayUI->convertTouchToNodeSpace((CCTouch *)pTouches->anyObject())))
	{
		//m_pTFRoomSend->attachWithIME();

	}

	if(m_gameStep != GAMESTEP_ADJUST)
	{
        return;
    }
    
    if(NULL == m_pMoveTouch && m_myGameTurn == m_gameTurn)
    {
        CArrow *pNewArrow =  m_pArcherLocal->BeginTouches(pTouches, pEvent);
        if(NULL != pNewArrow)
        {
            m_pArrowFlying = pNewArrow;
            return;
        }
    }
    
    for(CCSetIterator iter = pTouches->begin(); iter != pTouches->end(); iter++)
    {
        CCTouch *pCurTouch = (CCTouch *)(*iter);
        
        if(NULL == m_pMoveTouch)
        {
            m_pMoveTouch = pCurTouch;
        }
        
        if(pCurTouch != m_pMoveTouch)
        {
            m_pScaleTouch = pCurTouch;
            m_bFirstScaleTouch = true;
			m_pCurScene->SetScaleCenter(m_pCurScene->GetTouchInMain(m_pMoveTouch));
        }
    }
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::ccTouchesMoved(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	
	if(m_gameStep != GAMESTEP_ADJUST)
	{
		return;
	}
    if(NULL != m_pArrowFlying &&  m_myGameTurn == m_gameTurn)
    {
        m_pArcherLocal->MoveTouches(pTouches, pEvent);
    }
    
    if(NULL != m_pMoveTouch && NULL == m_pScaleTouch)
    {
        static cocos2d::CCPoint ptLast = ccp(0, 0);
        
        if(m_bFirstMoveTouch)
        {
            ptLast = convertTouchToNodeSpace(m_pMoveTouch);
            m_bFirstMoveTouch = false;
        }
        
        float xAdd = (ptLast.x - convertTouchToNodeSpace(m_pMoveTouch).x) / CGameGlobal::GetInstance()->m_resScale;
        float yAdd = (ptLast.y - convertTouchToNodeSpace(m_pMoveTouch).y) / CGameGlobal::GetInstance()->m_resScale;
        ptLast = convertTouchToNodeSpace(m_pMoveTouch);
        
        m_pCurScene->MoveMainScene(xAdd, yAdd);
    }
    
    if(NULL != m_pScaleTouch)
    {
        
        CCPoint ptTouch1 = convertTouchToNodeSpace(m_pMoveTouch);
        CCPoint ptTouch2 = convertTouchToNodeSpace(m_pScaleTouch);
        CCPoint ptTouchCenter = ptTouch1;
        
        static float lastDist;
        if(m_bFirstScaleTouch)
        {
            lastDist = ccpDistance(ptTouch1, ptTouch2);
            m_bFirstScaleTouch = false;
        }
        
        float curDist = ccpDistance(ptTouch1, ptTouch2);
        float distDiff = curDist - lastDist;
        
        m_pCurScene->ScaleMainScene(distDiff);
        
        return;
    }
 
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{

    for(CCSetIterator iter = pTouches->begin(); iter != pTouches->end(); iter++)
    {
        CCTouch *pCurTouch = (CCTouch *)(*iter);
        
        if(pCurTouch == m_pScaleTouch)
        {
            m_pScaleTouch = NULL;
            m_bFirstScaleTouch = true;
        }
        
        if(pCurTouch == m_pMoveTouch)
        {
            m_pMoveTouch = NULL;
            m_bFirstMoveTouch = true;
        }
    }
    
    if(m_pMoveTouch == NULL && m_pScaleTouch != NULL)
    {
        m_pMoveTouch = m_pScaleTouch;
        m_bFirstScaleTouch = true;
        m_bFirstMoveTouch  = true;
        m_pCurScene->SetScaleCenter(m_pCurScene->GetTouchInMain(m_pScaleTouch));
        m_pScaleTouch = NULL;
    }
    

    if(m_myGameTurn != m_gameTurn || m_gameStep != GAMESTEP_ADJUST)
    {
        return;
    }
    
	if(pTouches->count() < 1|| !m_pArcherLocal->IsValid())
	{
		return;
	}
    
    if(NULL != m_pArrowFlying)
    {
        if(!m_pArcherLocal->DisableTouches(pTouches, pEvent))
        {
            
            return;
        }
        
        m_curTime    = 0;
        m_gameStep = GAMESTEP_PRESHOOT;
        m_pCurScene->ScaleMainWithCenter(m_pArcherLocal->GetPos(), 1.0f);
        EnableButtons(false);
		m_userScale = m_pCurScene->GetMainScale();
        
#ifndef GAME_USEAI
        AttactSend attackSend;
        
        attackSend.x = m_pArcherLocal->GetPos().x;
        attackSend.power = m_pArcherLocal->GetPower() * 30;
        attackSend.angle = m_pArcherLocal->GetCurAngle();
        CCPoint ptArrow =  CGameGlobal::GetInstance()->RestoreResToLogicPos(m_pArrowFlying->TailToHead(m_pCurScene->GetPosInMain(m_pArcherLocal->GetLeftHandPos()), m_pArcherLocal->GetCurAngle()));
        attackSend.ArrowX = ptArrow.x;
        attackSend.ArrowY = ptArrow.y;
        attackSend.direction = m_pArcherLocal->IsFlip();
        
        m_pServer->SendFightAttack(attackSend);
#endif
    }
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::ccTouchesCancelled(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
    
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::onReceiveMsg(int aID, int event, const void *pData)
{
    if(aID == BTN_GAMESCENE_SENDMSG)
	{

		const char *curChat =  m_pTFRoomSend->getString();

		if(strlen(curChat) == 0 || strlen(curChat) > 255)
		{
			return;
		}
		//m_strChat += curChat;
		
		m_pLabelChat[m_lastChatLabel]->setPosition(ccpAdjustRes(100, 140));

		std::string strLocal = "我：";
		char szLocal[512];
		strcpy(szLocal, strLocal.c_str());
		strcat(szLocal, curChat);
		m_pLabelChat[m_lastChatLabel]->setString(szLocal);

		for(int i=0; i<CHATLABEL_MAX; i++)
		{
			if(i == m_lastChatLabel)
			{
				continue;
			}

			float curY = m_pLabelChat[i]->getPosition().y  + 20 * CGameGlobal::GetInstance()->m_resScale;

			if(curY / CGameGlobal::GetInstance()->m_resScale > 180)
			{
				curY = 140 * CGameGlobal::GetInstance()->m_resScale;
			}
			m_pLabelChat[i]->setPosition(ccp(m_pLabelChat[i]->getPosition().x, curY));

		}

		m_lastChatLabel--;
		if(m_lastChatLabel < 0)
		{
			m_lastChatLabel = CHATLABEL_MAX - 1;
		}

#ifndef GAME_USEAI
		m_pServer->SendRoomChat(curChat, strlen(curChat) + 1);
#endif
		m_pTFRoomSend->setString("");
	}
}

//------------------------------------------------------------------------------------------------------------/
void CGameScene::enemyMove(int id, const Move &moveInfo)
{
   
    Move *pNew = new Move;
    memcpy(pNew, &moveInfo, sizeof(moveInfo));
    
    m_qEnemyMove.push(pNew);
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::attackSuccess(int id, const AttactRecv &attackInfo)
{
    AttactRecv *pNew = new AttactRecv;
    memcpy(pNew, &attackInfo, sizeof(attackInfo));

	if(id == m_pArcherLocal->GetID())
	{
		 m_qLocalAttack.push(pNew);
	}
	else if(id == m_pArcherTarget->GetID())
	{
		 m_qEnemyAttack.push(pNew);
	}
   
}
void CGameScene::roomChat(int id, const char *szRoom, int len)
{
	char szRecv[512];
	if(s_initData.position1ID == m_pArcherTarget->GetID())
	{
		strcpy(szRecv, s_initData.position1Name);
	}
	else
	{
		strcpy(szRecv, s_initData.position2Name);

	}


    std::string str = g_GetUTF8(" :");

	
	strcat(szRecv, str.c_str());
	strcat(szRecv, szRoom);
	m_pLabelChat[m_lastChatLabel]->setPosition(ccpAdjustRes(100, 140));
	m_pLabelChat[m_lastChatLabel]->setString(szRecv);

	for(int i=0; i<CHATLABEL_MAX; i++)
	{
		if(i == m_lastChatLabel)
		{
			continue;
		}

		float curY = m_pLabelChat[i]->getPosition().y  + 20 * CGameGlobal::GetInstance()->m_resScale;

		if(curY / CGameGlobal::GetInstance()->m_resScale > 180)
		{
			curY = 140 * CGameGlobal::GetInstance()->m_resScale;
		}
		m_pLabelChat[i]->setPosition(ccp(m_pLabelChat[i]->getPosition().x, curY));

	}

	m_lastChatLabel--;
	if(m_lastChatLabel < 0)
	{
		m_lastChatLabel = CHATLABEL_MAX - 1;
	}

}
//-------------------------------------------------------------------------------------------------------------/
void CGameScene::gameServerRejected()
{
	CLoginScene::Show();

}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::gameServerLost()
{
	CLoginScene::Show();
}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::userLost()
{
   CRoomScene::Show();
}
//-------------------------------------------------------------------------------------------------------------/
void CGameScene::OnUpdate(cocos2d::ccTime dt)
{
#ifndef GAME_USEAI
	m_pServer->ReceivePacket();
#endif
    

    UpdateObjects(dt);
    
    
    
    //if(m_gameStep != GAMESTEP_SHOOT)
    {
        if(m_pCurScene->UpdateScale(dt))
        {
            return;
        }
    }
    
    if(m_gameWaitTimer > 0)
    {
        m_gameWaitTimer -= dt;
        return;
    }

	switch (m_gameStep)
	{
	case GAMESTEP_BEGIN:
		{
			GameBegin(dt);
		}
		break;

	case GAMESTEP_PREPARE:
		{
			MoveTable(dt);
		}
		break;

	case GAMESTEP_ADJUST:
		{
			ArcherAdjust(dt);
		}
		break;

	case GAMESTEP_PRESHOOT:
		{
			PreShoot(dt);
		}
		break;

	case GAMESTEP_SHOOT:
		{
 			ArcherShoot(dt);
		}
		break;

	case GAMESTEP_HURT:
		{
			HurtStep(dt);
		}
		break;

	case GAMESTEP_CHANGETURN:
		{
			ChangeTurn(dt);
		}
		break;
	}

}

//-------------------------------------------------------------------------------------------------------------/
void CGameScene::UpdateObjects(cocos2d::ccTime dt)
{
    static float t;
	t += dt;
	if(NULL != m_pArcherLocal)
	{
		m_pArcherLocal->UpdateAnimation((long)(t*1000), true);
        m_pArcherLocal->UpdateAutoShoot(dt);
	}
    
	if(NULL != m_pArcherTarget)
	{
		m_pArcherTarget->UpdateAnimation((long)(t*1000), true);
        m_pArcherTarget->UpdateAutoShoot(dt);
	}
	m_pCurScene->updateScene(dt);

    m_pArcherLeft->SetPos(ccp(m_pArcherLeft->GetPos().x, m_pCurScene->GetLeftTableHeight()));
    m_pArcherRight->SetPos(ccp(m_pArcherRight->GetPos().x, m_pCurScene->GetRightTableHeight()));
}



//-------------------------------------------------------------------------------------------------------------/
bool CGameScene::UpdateLogicWorld(cocos2d::ccTime curTime)
{
    if(NULL == m_pArrowFlying)
    {
        return false;
    }
    if(m_pArrowFlying->ProcessLogicTime(curTime))
    {
        
        return true;
    }
    
	return false;
}

void CGameScene::GameBegin(cocos2d::ccTime dt)
{

	static int sLocalStep = 0;

	if(sLocalStep == 0)
	{
		m_pCurScene->ScaleMainWithCenter(m_pArcherLocal->GetPos(), 1.0f, 100.0f);
		sLocalStep =1;
		m_gameWaitTimer = 1.0f;
	}
	else if(sLocalStep == 1)
	{
		m_pCurScene->ScaleMainWithCenter(m_pArcherTarget->GetPos(), 1.0f, 100.0f);
		sLocalStep =2;
		m_gameWaitTimer = 1.0f;
	}
	else if(sLocalStep == 2)
	{
		m_pCurScene->ScaleMainWithCenter(m_pArcherLocal->GetPos(), 1.0f, 100.0f);
		sLocalStep = 0;
		m_gameStep = GAMESTEP_PREPARE;
	}


}
//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::MoveTable(cocos2d::ccTime dt)
{
	static int sLocalStep = 0;

	if(!m_pCurScene->moveTable(dt))
	{
		if(NULL == m_pArcherLeft->GetCurArrow())
		{
			m_pArcherLeft->AddArrow();
		}
		if(NULL == m_pArcherRight->GetCurArrow())
		{
			m_pArcherRight->AddArrow();
		}

		if(sLocalStep == 0)
		{
			m_gameWaitTimer = 1.0f;
			sLocalStep = 1;

		}
		else
		{
			if(m_gameTurn == GAMETURN_LEFT)
			{
				m_pCurScene->ScaleMainWithCenter(m_pArcherLeft->GetPos(), m_userScale);
			}
			else 
			{
				m_pCurScene->ScaleMainWithCenter(m_pArcherRight->GetPos(), m_userScale);
			}

			sLocalStep = 0;
			m_gameStep = GAMESTEP_ADJUST;
		}
	}
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::ArcherAdjust(cocos2d::ccTime dt)
{
    if(m_gameTurn == m_myGameTurn)
    {
        CCPoint ptCur = m_pArcherLocal->GetPos();
        
        bool bCanLeft = true;
        bool bCanRight = true;
        if(m_myGameTurn == GAMETURN_LEFT)
        {
            if(ptCur.x >= m_pCurScene->GetLeftMax())
            {
                bCanRight = false;
            }
            else if(ptCur.x <= m_pCurScene->GetLeftMin())
            {
                bCanLeft  = false;
            }
        }
        else
        {
            if(ptCur.x >= m_pCurScene->GetRightMax())
            {
                bCanRight = false;
            }
            else if(ptCur.x <= m_pCurScene->GetRightMin())
            {
                bCanLeft  = false;
            }
        }
        
        if(m_pBtnMoveLeft->IsButtonDown())
        {
            if(bCanLeft && m_pArcherLocal->IsCanMove())
            {
                m_pArcherLocal->MoveLeft();
            }
            
            
        }
        else if(m_pBtnMoveRight->IsButtonDown())
        {
            if(bCanRight && m_pArcherLocal->IsCanMove())
            {
                m_pArcherLocal->MoveRight();
            }
        }
        else
        {
            m_pArcherLocal->MoveStop();
        }
        
        static float sendTime = 0;
        sendTime += dt;
        
        if(sendTime > 1.0f)
        {
            Move moveSend;
            
            moveSend.direction = m_pArcherLocal->IsFlip();
            moveSend.x         = (short)m_pArcherLocal->GetPos().x;
            moveSend.power     = m_pArcherLocal->GetPower();
            moveSend.angle     = m_pArcherLocal->GetCurAngle();
            
            m_pServer->SendFightMove(moveSend);
            
            sendTime = 0;
        }
    }
    else
    {
#ifdef GAME_USEAI
        float startAngle = rand() % 15;
        float s = 1;
        if(m_pArcherTarget->IsFlip())
        {
            startAngle = 180;
            s = -1;
        }
        m_pArcherTarget->AutoShoot(120 * 30, startAngle + s *(rand() % 15), m_pArcherTarget->GetPos().x,  0, m_pArcherTarget->IsFlip());
        m_gameStep = GAMESTEP_PRESHOOT;
#else
        // 等待网络
        
        
        if(m_qEnemyAttack.size() > 0)
        {
            m_gameStep = GAMESTEP_PRESHOOT;
            
            while (m_qEnemyMove.size() > 0) 
            {
                Move *pTop = m_qEnemyMove.front();
                m_qEnemyMove.pop();
                delete pTop;
            }
            
            AttactRecv *pAttack = m_qEnemyAttack.front();
            m_pArcherTarget->AutoShoot(pAttack->power, pAttack->angle, pAttack->x, 0, pAttack->direction);
        }
        else
        {
            if(m_qEnemyMove.size() > 0)
            {
                Move *pTop = m_qEnemyMove.front();
                m_qEnemyMove.pop();
                
                m_pArcherTarget->AutoShoot(pTop->power, pTop->angle, pTop->x, 0, pTop->direction);
                
                delete pTop;
            }
        }
        
#endif
    }

    
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::PreShoot(cocos2d::ccTime dt)
{
    if(m_gameTurn == m_myGameTurn)
    {
#ifdef GAME_USEAI
        CCPoint ptArrow =  CGameGlobal::GetInstance()->RestoreResToLogicPos(m_pArrowFlying->TailToHead(m_pCurScene->GetPosInMain(m_pArcherLocal->GetLeftHandPos()), m_pArcherLocal->GetCurAngle()));
		
        m_pArrowFlying = m_pArcherLocal->Shoot(ccp(ptArrow.x, ptArrow.y), m_pArcherLocal->GetCurAngle(), m_pArcherLocal->GetPower() * 30);
        
        float time = 0;
        while (!UpdateLogicWorld(time)) {
            time += 0.01f;
        }
        
        m_endTime = time;
        
        
#else
     
        
        if(m_qLocalAttack.size() == 0)
        {
            return;
        }
        
        AttactRecv *pAttack = m_qLocalAttack.front();
        m_pArrowFlying = m_pArcherLocal->Shoot(ccp(pAttack->ArrowX, pAttack->ArrowY), pAttack->angle, pAttack->power);
        
        long endTime = 0.1f;
        endTime = (long)pAttack->endTime;
        
        m_endTime = pAttack->endTime / 1000.0f;
#endif
		//m_pCurScene->ScaleMainWithCenter(m_pArcherLocal->GetPos(), 0.75f, 30.0f);
    }
    else
    {
        if(m_pArcherTarget->UpdateAutoShoot(dt))
        {
            return;
        }
#ifdef GAME_USEAI
		m_pArrowFlying = m_pArcherTarget->GetCurArrow();

		CCPoint ptArrow =  CGameGlobal::GetInstance()->RestoreResToLogicPos(m_pArrowFlying->TailToHead(m_pCurScene->GetPosInMain(m_pArcherTarget->GetLeftHandPos()), m_pArcherTarget->GetCurAngle()));

		m_pArrowFlying = m_pArcherTarget->Shoot(ccp(ptArrow.x, ptArrow.y), m_pArcherTarget->GetCurAngle(), m_pArcherTarget->GetPower());
		float time = 0;
		while (!UpdateLogicWorld(time)) {
			time += 0.01f;
		}

		m_endTime = time;
#else
        AttactRecv *pAttack = m_qEnemyAttack.front();
        m_pArrowFlying =  m_pArcherTarget->Shoot(ccp(pAttack->ArrowX, pAttack->ArrowY), pAttack->angle, pAttack->power);
        m_endTime = pAttack->endTime / 1000.0f;
#endif
		//m_pCurScene->ScaleMainWithCenter(m_pArcherTarget->GetPos(), 0.75f, 1.0f);
    }
    m_pCurScene->SetMainScale(0.75, 0.5f);
    m_gameStep = GAMESTEP_SHOOT;

}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::ArcherShoot(cocos2d::ccTime dt)
{
    dt *= 1.3f;
    if(m_curTime + dt < m_endTime)
    {
        m_curTime += dt;
    }
    else
    {
        m_curTime = m_endTime;
    }
    
    
    if(NULL != m_pArrowFlying)
    {
        m_pArrowFlying->ProcessTime(m_curTime);
		MyPoint ptCurArrow = m_pArrowFlying->GetCurPos();
		m_pCurScene->FollowObject(ccp(ptCurArrow.x, ptCurArrow.y));
    }
    
    if(m_curTime == m_endTime)
    {
		bool bHurt = false;
        int curHpLeft;
        int curHpRight;
#ifdef GAME_USEAI
        
        if(m_gameTurn == m_myGameTurn)
        {
            if(m_pArcherTarget->CheckHurt(m_pArcherLocal->GetCurArrowInfo(), m_pArrowFlying->GetSprite()))
            {
                m_pArcherTarget->SetHp(m_pArcherTarget->GetHP() - 35);
				bHurt = true;
            }
        }
        else
        {
            if(m_pArcherLocal->CheckHurt(m_pArcherTarget->GetCurArrowInfo(), m_pArrowFlying->GetSprite()))
            {
                m_pArcherLocal->SetHp(m_pArcherLocal->GetHP() - 35);
				bHurt = true;
            }
        }
        
        curHpLeft = m_pArcherLeft->GetHP();
        curHpRight = m_pArcherRight->GetHP();
#else
        AttactRecv *pAttackRecv;
        if(m_gameTurn == m_myGameTurn)
        {
            pAttackRecv = m_qLocalAttack.front();
            m_pArcherTarget->Hurt(pAttackRecv->hit, m_pArcherLocal->GetCurArrowInfo(), m_pArrowFlying->GetSprite());
        }
        else
        {
            pAttackRecv = m_qEnemyAttack.front();
            m_pArcherLocal->Hurt(pAttackRecv->hit, m_pArcherTarget->GetCurArrowInfo(), m_pArrowFlying->GetSprite());
        }
        
        curHpLeft = pAttackRecv->position1HP;
        curHpRight = pAttackRecv->position2HP;

		if(pAttackRecv->hit > 0)
		{
			bHurt = true;
		}
        
#endif
		if(bHurt)
		{
			if(NULL != m_pArrowFlying)
			{
				m_pArrowFlying->GetSprite()->setIsVisible(false);
			}
		}
        char szFormat[128];
        sprintf(szFormat, "%s : %d", s_initData.position1Name, curHpLeft);
        m_pFntLeftHp->setString(szFormat);
        sprintf(szFormat, "%s : %d", s_initData.position2Name, curHpRight);
        m_pFntRightHp->setString(szFormat);
        
        if(curHpLeft <= 0 || curHpRight <= 0)
        {
            if(curHpLeft <= 0)
            {
                m_pArcherLeft->Dead(m_pArcherLeft->GetPos().y);
            }
            else
            {
                m_pArcherRight->Dead(m_pArcherRight->GetPos().y);
            }
            
            GameOver();
            return;
        }
        
        m_curTime       = 0;
       
        
        AddArrow(m_pArrowFlying);
        m_pArrowFlying = NULL;
        m_pCurScene->LocateCurOrgin();

		if(bHurt)
		{
			m_gameStep = GAMESTEP_HURT;
			
		}
		else
		{
			m_gameStep      = GAMESTEP_CHANGETURN;
			m_gameWaitTimer = 1.0f;
		}

        
    }
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::HurtStep(cocos2d::ccTime dt)
{
	if(!m_pCurScene->Shake(dt, 1, 10))
	{
		m_gameStep = GAMESTEP_CHANGETURN;
		m_gameWaitTimer = 1.0f;
	}
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
bool CGameScene::ChangeTurn(cocos2d::ccTime dt)
{
    m_gameStep = GAMESTEP_PREPARE;
    RemoveTopArrow();
    
#ifdef GAME_USEAI
	m_pCurScene->SetTableDist(275 + rand() % 200, 275 + rand() % 200);
#else
    AttactRecv *pAttackRecv;
    if(m_gameTurn == m_myGameTurn)
    {
        if(m_qLocalAttack.size() == 0)
        {
            return false;
        }
        pAttackRecv = m_qLocalAttack.front();
        m_qLocalAttack.pop();
    }
    else
    {
        if(m_qEnemyAttack.size() == 0)
        {
            return false;
        }
        pAttackRecv = m_qEnemyAttack.front();
        m_qEnemyAttack.pop();
    }
    
	m_pCurScene->SetTableDist(pAttackRecv->newposition1y, pAttackRecv->newposition2y);
    delete pAttackRecv;
#endif
    
    
   
    
    m_pCurScene->ScaleMainWithCenter(ccp(SCREEN_WIDTH , 0), 0.5f);
    
    if(m_gameTurn == GAMETURN_RIGHT)
    {
        m_gameTurn = GAMETURN_LEFT;
    }
    else
    {
        m_gameTurn = GAMETURN_RIGHT;
    }
    
    if(m_gameTurn == m_myGameTurn)
    {
        EnableButtons(true);
    }
    else
    {
        EnableButtons(false);
    }
    
    return true;
}


//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::InitUI()
{
    m_pBtnMoveLeft = CCocosButton::CreateButton(BTN_GAMESCENE_MOVELEFT, this, CCocosButton::TYPE_SCALE, false, "UI/b1.png");
    m_pBtnMoveRight = CCocosButton::CreateButton(BTN_GAMESCENE_MOVERIGHT, this, CCocosButton::TYPE_SCALE, false, "UI/f1.png");
	m_pBtnSend      = CCocosButton::CreateButton(BTN_GAMESCENE_SENDMSG, this, CCocosButton::TYPE_SCALE, false, "UI/btnSend.png");
    m_pLayUI->addChild(m_pBtnMoveLeft);
    m_pLayUI->addChild(m_pBtnMoveRight);
	m_pLayUI->addChild(m_pBtnSend);
    m_pBtnMoveLeft->setPosition(ccpAdjust(100, 60));
    m_pBtnMoveRight->setPosition(ccpAdjust(SCREEN_WIDTH - 100, 60));
	m_pBtnSend->setPosition(ccpAdjustRes(SCREEN_WIDTH - 100, 120));

	m_pBtnSend->show(false);
    
	m_pTFRoomSend = CCTextFieldTTF::textFieldWithPlaceHolder("<touch here to send message>", "Arial", 16);
	m_pLayUI->addChild(m_pTFRoomSend);
	m_pTFRoomSend->setAnchorPoint(ccp(0, 0.5));
	m_pTFRoomSend->setPosition(ccpAdjust(100, 120));
	m_pTFRoomSend->setIsVisible(false);

	for(int i=0; i<3; i++)
	{
		m_pLabelChat[i] = CCLabelTTF::labelWithString("","Arial", 16);
		m_pLabelChat[i]->setPosition(ccpAdjustRes(100, 120 + 20 * i + 20));
		m_pLayUI->addChild(m_pLabelChat[i]);
		m_pLabelChat[i]->setAnchorPoint(ccp(0, 0.5));
	}
	
    if(m_myGameTurn == m_gameTurn)
    {
        EnableButtons(true);
    }
    else
    {
        EnableButtons(false);
    }
    
    m_pFntLeftHp = CCLabelTTF::labelWithString("", "Arial", 16);
	m_pLayUI->addChild(m_pFntLeftHp, 100);
	m_pFntLeftHp->setAnchorPoint(ccp(0, 1));
	m_pFntLeftHp->setPosition(ccpAdjust(0, SCREEN_HEIGHT));
    
    m_pFntRightHp = CCLabelTTF::labelWithString("", "Arial", 16);
	m_pLayUI->addChild(m_pFntRightHp, 100);
	m_pFntRightHp->setAnchorPoint(ccp(1, 1));
	m_pFntRightHp->setPosition(ccpAdjust(SCREEN_WIDTH, SCREEN_HEIGHT));

	char szFormat[128];
	sprintf(szFormat, "%s : %d", s_initData.position1Name,s_initData.position1HP);
	m_pFntLeftHp->setString(szFormat);
	sprintf(szFormat, "%s : %d", s_initData.position2Name, s_initData.position2HP);
	m_pFntRightHp->setString(szFormat);
    
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::Restart()
{
#ifdef GAME_USEAI
    this->Show();
#else
    CRoomScene::Show();
#endif
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::GameOver()
{
    m_gameStep = GAMESTEP_OVER;
    CleanArrows();
    runAction(CCSequence::actionOneTwo(CCDelayTime::actionWithDuration(8.0f), CCCallFunc::actionWithTarget(this, callfunc_selector(CGameScene::Restart))));
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::EnableButtons(bool bEnable)
{
    m_pBtnMoveLeft->setEnable(bEnable);
    m_pBtnMoveRight->setEnable(bEnable); 
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::AddArrow(CArrow *pNewArrow)
{
	if(NULL != pNewArrow)
	{
		m_qArrow.push(pNewArrow);
	}
    
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::RemoveTopArrow()
{
    if(m_qArrow.size() >= 1)
    {
        CArrow *pArrow = m_qArrow.front();
        m_qArrow.pop();
        pArrow->Remove();
        delete pArrow;
    }
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::CleanArrows()
{
    while(m_qArrow.size() >= 1)
    {
        CArrow *pArrow = m_qArrow.front();
        m_qArrow.pop();
        pArrow->Remove();
        delete pArrow;
    }
    
    if(NULL != m_pArrowFlying)
    {
        m_pArrowFlying->Remove();
        m_pArrowFlying = NULL;
    }
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::InitData()
{
#ifdef GAME_USEAI
    s_initData.position = 2;
    s_initData.scene    = 1;
    s_initData.action   = true;
    s_initData.platforxmin = 150;
    s_initData.platforxmax = 350;
    s_initData.ArchersPower = 85;
    
    s_initData.position1Role = 1;
    s_initData.position1HP  = 100;
    s_initData.position1X   = 400;
    s_initData.position1Y   = rand() % 200 + 275;
    s_initData.position1ArrowID = 1;
    
    s_initData.position2Role = 1;
    s_initData.position2HP  = 100;
    s_initData.position2X   = (short)(WORLD_WIDTH - 400);
    s_initData.position2Y   = rand() % 200 + 275;
    s_initData.position1ArrowID = 1;
#endif
    
    if(s_initData.position == 1)
    {
        m_myGameTurn = GAMETURN_LEFT;
    }
    else
    {
        m_myGameTurn = GAMETURN_RIGHT;
    }
    
    if(s_initData.action)
    {
        m_gameTurn = m_myGameTurn;
    }
    else
    {
        if(m_myGameTurn == GAMETURN_LEFT)
        {
            m_gameTurn = GAMETURN_RIGHT;
        }
        else
        {
            m_gameTurn = GAMETURN_LEFT;
        }
    }
    
	m_pCurScene->SetTableDist(s_initData.position1Y, s_initData.position2Y);

    m_gameStep = GAMESTEP_BEGIN;
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::ReleaseData()
{
    CleanArrows();
    
    while (m_qLocalAttack.size() > 0) 
    {
        AttactRecv *pRecv = m_qLocalAttack.front();
        m_qLocalAttack.pop();
        delete pRecv;
    }
    
    while (m_qEnemyAttack.size() > 0) 
    {
        AttactRecv *pRecv = m_qEnemyAttack.front();
        m_qEnemyAttack.pop();
        delete pRecv;
    }
    
    while (m_qEnemyMove.size() > 0) 
    {
        Move *pRecv = m_qEnemyMove.front();
        m_qEnemyMove.pop();
        delete pRecv;
    }
}

//-----------------------------------------------------------------------------------------------------------------------------------------/
void CGameScene::InitPlayers()
{
    CArcherManager::SetSceneInfo(m_pCurScene->GetMainLayer(), ZORDER_PLAYER);
    
    m_pArcherLeft  = CArcherManager::CreateArcher(s_initData.position1ID, false, s_initData.position1Role, 1,  1);
    m_pArcherRight = CArcherManager::CreateArcher(s_initData.position2ID, true, s_initData.position2Role, 1, 1);
    
    if(m_myGameTurn == GAMETURN_LEFT)
    {
        m_pArcherLocal = m_pArcherLeft;
        m_pArcherTarget = m_pArcherRight;
    }
    else
    {
        m_pArcherLocal = m_pArcherRight;
        m_pArcherTarget = m_pArcherLeft;
    }
	
    m_pArcherLocal->AddTarget(m_pArcherTarget);
    m_pArcherTarget->AddTarget(m_pArcherLocal);
    
    m_pArcherLeft->SetPos(ccp(s_initData.position1X ,  m_pCurScene->GetLeftTableHeight()));
    m_pArcherRight->SetPos(ccp(s_initData.position2X , m_pCurScene->GetRightTableHeight()));
}